package ext.tianma.project.relatedproduct;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import ext.generic.erp.common.CommonUtil;

public class ProjectAttributeMappingUtil {
	private static String clazz = ProjectAttributeMappingUtil.class.getName() ;
	
	private static Map<String,String> projectAttributesMapping = new HashMap<String,String>() ;
	
	private static final String CONFIG_FILE = "Project_Attributes_Mapping.xml" ;
	
	private static final ProjectAttributeMappingUtil instance = new ProjectAttributeMappingUtil() ;
	
	private ProjectAttributeMappingUtil(){
		String filePath = ProjectAttributeMappingUtil.class.getResource("").getPath() +  CONFIG_FILE ;
		
		parse( filePath ) ;
	}
	
	public static ProjectAttributeMappingUtil getInstance(){
		return instance ;
	}
	
	public Map<String, String> getProjectAttributesMapping() {
		return projectAttributesMapping;
	}

	private void parse(String file){
		if( file == null ){
			return ;
		}
		
		try{
			//获取XML的DOM对象
			DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
			DocumentBuilder documentBuilder = fac.newDocumentBuilder();
			Document document = documentBuilder.parse(file);
			
			if(document == null){
				System.out.println(">>>>> Error Info : "+ clazz + ".parse(String file) : document == null ");
				
				return ;
			}else{
				initProjectAttributesMapping( document ) ;
			}
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			
		}
	}
	
	private Map<String,String> initProjectAttributesMapping(Document document){
		
		Map<String,String> map = null ;
		
		NodeList nodeList = document.getElementsByTagName( "attribute" );
		
		if( nodeList != null ){
			int size = nodeList.getLength() ;
			
			System.out.println( "size :" + size );
			
			for(int i=0 ; i < size ; i++ ){
				Node node = nodeList.item(i) ;
				
				if( node != null && node instanceof Element){
					Element element = ( Element ) node ;
					
					String rfqAtt = element.getAttribute("dbColumn") ;
					String projectAtt = element.getAttribute("ibaName") ;
					
					if( ( rfqAtt != null ) && ( !rfqAtt.equals("") ) && ( projectAtt != null ) && ( ! projectAtt.equals("") ) ){

						projectAttributesMapping.put(rfqAtt, projectAtt);
					}
				}
			}
		}
		
		if( map == null ){
			map = new HashMap<String,String>() ; 
		}
		
		return map ;
	}
	
	public static void main(String[] args) {
		
		CommonUtil.printMap(ProjectAttributeMappingUtil.getInstance().getProjectAttributesMapping()) ;	

	}
}
